/**
 * @description 登录、获取用户信息、退出登录、清除token逻辑，不建议修改
 */
import Vue from 'vue'
import { getUserInfo, login, logout, getAreaTree } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/token'
import { resetRouter } from '@/router'
import { isArray, isString } from '@/utils/validate'
import { title, tokenName } from '@/config'
import HeadSvg from '../../assets/head.svg'

// 转换省市区树状列表
function reTreeName(list) {
  const reCall = (item) => {
    item.value = item.areaName + ':' + item.areaCode
    item.label = item.areaName
    // item.leaf = 'leaf'
    if (Array.isArray(item.children) && item.children.length > 0) {
      item.children.forEach((v) => {
        reCall(v)
      })
    }
  }
  list.forEach((v) => {
    reCall(v)
  })
}

const state = () => ({
  token: getToken(),
  username: '游客',
  avatar: HeadSvg,
  treeList: [], // 省市区树状列表
})
const getters = {
  token: (state) => state.token,
  username: (state) => state.username,
  avatar: (state) => state.avatar,
  treeList: (state) => state.treeList,
}
const mutations = {
  /**
   * @description 设置token
   * @param {*} state
   * @param {*} token
   */
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  /**
   * @description 设置用户名
   * @param {*} state
   * @param {*} username
   */
  setUsername(state, username) {
    state.username = username
  },
  /**
   * @description 设置头像
   * @param {*} state
   * @param {*} avatar
   */
  setAvatar(state, avatar) {
    state.avatar = avatar
  },
  setTree(state, treeList) {
    state.treeList = treeList
  },
}
const actions = {
  /**
   * @description 登录拦截放行时，设置虚拟角色
   * @param {*} { commit, dispatch }
   */
  setVirtualRoles({ commit, dispatch }) {
    dispatch('acl/setFull', true, { root: true })
    commit('setAvatar', HeadSvg)
    commit('setUsername', 'admin(未开启登录拦截)')
  },
  /**
   * 设置省市区列表
   * */
  async setTreeList({ state, commit }) {
    // 不重复获取
    if (Array.isArray(state.treeList) && state.treeList.length > 0) {
      return
    }
    try {
      const res = await getAreaTree()
      // console.log(res)
      if (res && Array.isArray(res.data)) {
        reTreeName(res.data)
        commit('setTree', res.data)
      }
    } catch (e) {
      console.log(e)
    }
  },
  /**
   * @description 登录
   * @param {*} { commit }
   * @param {*} userInfo
   */
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    if (!res.data || res.status === 50009) {
      Vue.prototype.$baseMessage(res.msg, 'error', 'vab-hey-message-error')
      throw res.msg
    }
    const { [tokenName]: token } = res.data
    if (token) {
      commit('setToken', token)
      const hour = new Date().getHours()
      const thisTime =
        hour < 8
          ? '早上好'
          : hour <= 11
          ? '上午好'
          : hour <= 13
          ? '中午好'
          : hour < 18
          ? '下午好'
          : '晚上好'
      Vue.prototype.$baseNotify(`欢迎登录${title}`, `${thisTime}！`)
    } else {
      const err = `登录接口异常，未正确返回${tokenName}...`
      Vue.prototype.$baseMessage(err, 'error', 'vab-hey-message-error')
      throw err
    }
  },
  /**
   * @description 获取用户信息接口 这个接口非常非常重要，如果没有明确底层前逻辑禁止修改此方法，错误的修改可能造成整个框架无法正常使用
   * @param {*} { commit, dispatch, state }
   * @returns
   */
  async getUserInfo({ commit, dispatch }) {
    const {
      data: { userName, avatar, roleList, resList, ability },
    } = await getUserInfo()
    /**
     * 检验返回数据是否正常，无对应参数，将使用默认用户名,头像,Roles和Ability
     * username {String}
     * avatar {String}
     * roles {List}
     * ability {List}
     */
    if (
      (userName && !isString(userName)) ||
      (avatar && !isString(avatar)) ||
      (roleList && !isArray(roleList)) ||
      (ability && !isArray(ability))
    ) {
      const err = 'getUserInfo核心接口异常，请检查返回JSON格式是否正确'
      Vue.prototype.$baseMessage(err, 'error', 'vab-hey-message-error')
      throw err
    } else {
      // 如不使用username用户名,可删除以下代码
      if (userName) commit('setUsername', userName)
      // 如不使用avatar头像,可删除以下代码
      if (avatar) commit('setAvatar', avatar)
      // 如不使用roles权限控制,可删除以下代码
      // 判断菜单权限
      if (Array.isArray(resList)) {
        dispatch('routes/setResList', resList, { root: true })
      }
      if (Array.isArray(roleList)) {
        const list = roleList.map((v) => v.code)
        dispatch('acl/setRole', list, { root: true })
      }
      // 如不使用ability权限控制,可删除以下代码
      if (ability) dispatch('acl/setAbility', ability, { root: true })
    }
  },
  /**
   * @description 退出登录
   * @param {*} { dispatch }
   */
  async logout({ dispatch }) {
    await logout()
    await dispatch('resetAll')
  },
  /**
   * @description 重置token、roles、ability、router、tabsBar等
   * @param {*} { commit, dispatch }
   */
  async resetAll({ commit, dispatch }) {
    commit('setUsername', '游客')
    commit('setAvatar', HeadSvg)
    commit('routes/setRoutes', [], { root: true })
    await dispatch('setToken', '')
    await dispatch('acl/setFull', false, { root: true })
    await dispatch('acl/setRole', [], { root: true })
    await dispatch('acl/setAbility', [], { root: true })
    await dispatch('tabs/delAllVisitedRoutes', null, { root: true })
    await resetRouter()
    removeToken()
  },
  /**
   * @description 设置token
   * @param {*} { commit }
   * @param {*} token
   */
  setToken({ commit }, token) {
    commit('setToken', token)
  },
  /**
   * @description 设置头像
   * @param {*} { commit }
   * @param {*} avatar
   */
  setAvatar({ commit }, avatar) {
    commit('setAvatar', avatar)
  },
}
export default { state, getters, mutations, actions }
